﻿using DotNetCore.CAP;
using EF.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace PaymentService.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class PaymentController : ControllerBase
    {
        /// <summary>
        /// cap发布对象
        /// </summary>
        public ICapPublisher CapPublisher { get; set; }
        /// <summary>
        /// 数据库连接
        /// </summary>
        public CommonContext Db { get; set; }
        /// <summary>
        /// 配置文件
        /// </summary>
        public IConfiguration Configuration { get; set; }

        /// <summary>
        /// mysql连接字符串
        /// </summary>
        public string MySqlConStr { get; set; }

        public PaymentController(ICapPublisher CapPublisher, CommonContext dbContext, IConfiguration configuration)
        {
            this.CapPublisher = CapPublisher;
            this.Db = dbContext;
            this.Configuration = configuration;
            this.MySqlConStr = configuration["CapSetting:MySqlConStr"];
        }

        /// <summary>
        /// 支付:有bug，因为CAP的MYSQL支持包，内部的MySqlConnection等对象是MysqlConnector包中的，并非Mysql.Data中的。使用ado的话，将会有bug
        /// </summary>
        /// <param name="paymentId"></param>
        /// <returns></returns>
        //[HttpPost("apply")]
        //public async Task<IActionResult> Apply([FromQuery]int paymentId)
        //{
        //    //1.调用支付：三方支付，银行卡支付
        //    //2. 支付成功。

        //    //更新支付状态，添加更新订单状态消息
        //    var dbPayment = await Db.Payment.FirstOrDefaultAsync(e => e.Id == paymentId);
        //    if (dbPayment == null&&dbPayment.ApplyStatus<1)
        //    {
        //        return new JsonResult(new { code = 1, msg = "数据未找到" });
        //    }

        //    //定义mq消息头
        //    IDictionary<string, string> dicHeader = new Dictionary<string, string>();
        //    dicHeader.Add("Playment", "用户【xxx】支付订单【xxx】");
        //    dicHeader.Add("UserId", $"{dbPayment.UserId}");
        //    dicHeader.Add("Version", "1.2");

        //    //事务提交数据，更新支付信息，新增支付消息
        //    using (var connection = new MySqlConnection(this.MySqlConStr))
        //    using (var transaction = connection.BeginTransaction(this.CapPublisher, true))
        //    {
        //        dbPayment.ApplyStatus = 1;
        //        this.Db.SaveChanges();
        //        CapPublisher.Publish("User_Apply_Order_Publish_Message", dbPayment, dicHeader);//带header
        //    }
        //    return new JsonResult(new { code = 0, msg = "支付成功" });
        //}



        /// <summary>
        /// 支付
        /// </summary>
        /// <param name = "paymentId" ></ param >
        /// < returns ></ returns >
        [HttpPost("apply")]
        public async Task<IActionResult> Apply([FromQuery] int paymentId)
        {
            //1.调用支付：三方支付，银行卡支付
            //2. 支付成功。

            //更新支付状态，添加更新订单状态消息
            var dbPayment = await Db.Payment.FirstOrDefaultAsync(e => e.Id == paymentId);
            if (dbPayment == null && dbPayment.ApplyStatus < 1)
            {
                return new JsonResult(new { code = 1, msg = "数据未找到" });
            }

            //定义mq消息头
            IDictionary<string, string> dicHeader = new Dictionary<string, string>();
            dicHeader.Add("Playment", "用户【xxx】支付订单【xxx】");
            dicHeader.Add("UserId", $"{dbPayment.UserId}");
            dicHeader.Add("Version", "1.2");

            //事务提交数据，更新支付信息，新增支付消息
            
            //using (var connection = new MySqlConnection(this.MySqlConStr))
            using (var transaction = Db.Database.BeginTransaction(this.CapPublisher, true))
            {
                dbPayment.ApplyStatus = 1;
                this.Db.SaveChanges();
                CapPublisher.Publish("User_Apply_Order_Publish_Message", dbPayment, dicHeader);//带header
            }
            return new JsonResult(new { code = 0, msg = "支付成功" });
        }
    }
}
